import { Response } from 'express';
import { 
  getGames, 
  getGameById, 
  createGame, 
  updateGame, 
  joinGame, 
  leaveGame, 
  startGame, 
  updatePlayerChips 
} from '../models/Game';
import { AuthRequest } from '../middleware/auth';

// 获取游戏列表
export const getGameList = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { status, limit = 10, offset = 0 } = req.query;
    
    const games = await getGames(
      status as string, 
      Number(limit), 
      Number(offset)
    );
    
    res.status(200).json({
      success: true,
      data: {
        games
      }
    });
  } catch (error) {
    console.error('获取游戏列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取游戏列表失败'
    });
  }
};

// 获取游戏详情
export const getGameDetails = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    
    if (!id || isNaN(Number(id))) {
      res.status(400).json({
        success: false,
        message: '无效的游戏ID'
      });
      return;
    }
    
    const game = await getGameById(Number(id));
    
    if (!game) {
      res.status(404).json({
        success: false,
        message: '游戏不存在'
      });
      return;
    }
    
    res.status(200).json({
      success: true,
      data: {
        game
      }
    });
  } catch (error) {
    console.error('获取游戏详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取游戏详情失败'
    });
  }
};

// 创建新游戏
export const createNewGame = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { name, maxPlayers = 6, smallBlind = 5, bigBlind = 10, buyIn = 1000 } = req.body;
    
    // 验证输入
    if (!name) {
      res.status(400).json({
        success: false,
        message: '游戏名称是必填项'
      });
      return;
    }
    
    if (!req.user) {
      res.status(401).json({
        success: false,
        message: '未授权访问'
      });
      return;
    }
    
    // 创建游戏
    const newGame = await createGame(
      name,
      req.user.id,
      maxPlayers,
      smallBlind,
      bigBlind,
      buyIn
    );
    
    res.status(201).json({
      success: true,
      message: '游戏创建成功',
      data: {
        game: newGame
      }
    });
  } catch (error) {
    console.error('创建游戏错误:', error);
    res.status(500).json({
      success: false,
      message: '创建游戏失败'
    });
  }
};

// 加入游戏
export const joinExistingGame = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    
    if (!id || isNaN(Number(id))) {
      res.status(400).json({
        success: false,
        message: '无效的游戏ID'
      });
      return;
    }
    
    if (!req.user) {
      res.status(401).json({
        success: false,
        message: '未授权访问'
      });
      return;
    }
    
    // 加入游戏
    const result = await joinGame(Number(id), req.user.id);
    
    if (!result.success) {
      res.status(400).json({
        success: false,
        message: result.message || '加入游戏失败'
      });
      return;
    }
    
    res.status(200).json({
      success: true,
      message: '成功加入游戏',
      data: {
        game: result.game
      }
    });
  } catch (error) {
    console.error('加入游戏错误:', error);
    res.status(500).json({
      success: false,
      message: '加入游戏失败'
    });
  }
};

// 离开游戏
export const leaveExistingGame = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    
    if (!id || isNaN(Number(id))) {
      res.status(400).json({
        success: false,
        message: '无效的游戏ID'
      });
      return;
    }
    
    if (!req.user) {
      res.status(401).json({
        success: false,
        message: '未授权访问'
      });
      return;
    }
    
    // 离开游戏
    const result = await leaveGame(Number(id), req.user.id);
    
    if (!result.success) {
      res.status(400).json({
        success: false,
        message: result.message || '离开游戏失败'
      });
      return;
    }
    
    res.status(200).json({
      success: true,
      message: '成功离开游戏',
      data: {
        game: result.game
      }
    });
  } catch (error) {
    console.error('离开游戏错误:', error);
    res.status(500).json({
      success: false,
      message: '离开游戏失败'
    });
  }
};

// 开始游戏
export const startExistingGame = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    
    if (!id || isNaN(Number(id))) {
      res.status(400).json({
        success: false,
        message: '无效的游戏ID'
      });
      return;
    }
    
    if (!req.user) {
      res.status(401).json({
        success: false,
        message: '未授权访问'
      });
      return;
    }
    
    // 开始游戏
    const result = await startGame(Number(id), req.user.id);
    
    if (!result.success) {
      res.status(400).json({
        success: false,
        message: result.message || '开始游戏失败'
      });
      return;
    }
    
    res.status(200).json({
      success: true,
      message: '游戏开始',
      data: {
        game: result.game
      }
    });
  } catch (error) {
    console.error('开始游戏错误:', error);
    res.status(500).json({
      success: false,
      message: '开始游戏失败'
    });
  }
};

// 更新玩家筹码
export const updatePlayerChipsInGame = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { chips } = req.body;
    
    if (!id || isNaN(Number(id))) {
      res.status(400).json({
        success: false,
        message: '无效的游戏ID'
      });
      return;
    }
    
    if (chips === undefined || isNaN(Number(chips))) {
      res.status(400).json({
        success: false,
        message: '无效的筹码数量'
      });
      return;
    }
    
    if (!req.user) {
      res.status(401).json({
        success: false,
        message: '未授权访问'
      });
      return;
    }
    
    // 更新玩家筹码
    const result = await updatePlayerChips(Number(id), req.user.id, Number(chips));
    
    if (!result.success) {
      res.status(400).json({
        success: false,
        message: result.message || '更新筹码失败'
      });
      return;
    }
    
    res.status(200).json({
      success: true,
      message: '筹码更新成功',
      data: {
        game: result.game
      }
    });
  } catch (error) {
    console.error('更新筹码错误:', error);
    res.status(500).json({
      success: false,
      message: '更新筹码失败'
    });
  }
};

// 处理游戏动作（下注、跟注、加注、弃牌、All In）- 无需认证版本
export const handleGameAction = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { type, amount, playerId } = req.body;
    
    if (!id || isNaN(Number(id))) {
      res.status(400).json({
        success: false,
        message: '无效的游戏ID'
      });
      return;
    }
    
    // 验证动作类型
    const validActions = ['check', 'call', 'raise', 'fold', 'all-in'];
    if (!validActions.includes(type)) {
      res.status(400).json({
        success: false,
        message: '无效的游戏动作类型'
      });
      return;
    }
    
    // 验证加注金额
    if (type === 'raise' && (amount === undefined || isNaN(Number(amount)) || amount <= 0)) {
      res.status(400).json({
        success: false,
        message: '无效的加注金额'
      });
      return;
    }
    
    // 获取游戏状态
    const game = await getGameById(Number(id));
    if (!game) {
      res.status(404).json({
        success: false,
        message: '游戏不存在'
      });
      return;
    }
    
    // 获取玩家ID - 如果没有认证用户，使用请求中的playerId
    let currentPlayerId: number;
    if (req.user) {
      currentPlayerId = req.user.id;
    } else if (playerId && !isNaN(Number(playerId))) {
      currentPlayerId = Number(playerId);
    } else {
      // 如果没有玩家ID，使用第一个玩家（用于演示）
      currentPlayerId = game.players[0]?.id;
    }
    
    // 查找当前玩家
    const currentPlayer = game.players.find(p => p.id === currentPlayerId);
    if (!currentPlayer) {
      res.status(403).json({
        success: false,
        message: '您不在此游戏中'
      });
      return;
    }
    
    // 验证是否是玩家回合
    if (game.currentPlayerPosition !== currentPlayer.position) {
      res.status(403).json({
        success: false,
        message: '现在不是您的回合'
      });
      return;
    }
    
    // 验证玩家是否已经弃牌或All In
    if (currentPlayer.hasFolded || currentPlayer.isAllIn) {
      res.status(403).json({
        success: false,
        message: '您已弃牌或All In，无法进行操作'
      });
      return;
    }
    
    // 验证All-in的合理性
    if (type === 'all-in' && currentPlayer.chips <= 0) {
      res.status(400).json({
        success: false,
        message: '您已经没有筹码，无法All-in'
      });
      return;
    }
    
    // 处理不同的游戏动作
    let updatedGame = { ...game };
    
    switch (type) {
      case 'check':
        // 过牌逻辑
        if (game.currentBet > currentPlayer.currentBet) {
          res.status(400).json({
            success: false,
            message: '当前有下注，无法过牌'
          });
          return;
        }
        break;
        
      case 'call':
        // 跟注逻辑
        const callAmount = game.currentBet - currentPlayer.currentBet;
        if (callAmount > currentPlayer.chips) {
          res.status(400).json({
            success: false,
            message: '筹码不足，无法跟注'
          });
          return;
        }
        // 更新玩家筹码和下注
        currentPlayer.chips -= callAmount;
        currentPlayer.currentBet = game.currentBet;
        updatedGame.pot += callAmount;
        break;
        
      case 'raise':
        // 加注逻辑
        const raiseAmount = Number(amount);
        const totalRaiseAmount = raiseAmount - currentPlayer.currentBet;
        if (totalRaiseAmount > currentPlayer.chips) {
          res.status(400).json({
            success: false,
            message: '筹码不足，无法加注'
          });
          return;
        }
        if (raiseAmount <= game.currentBet) {
          res.status(400).json({
            success: false,
            message: '加注金额必须大于当前下注'
          });
          return;
        }
        // 更新玩家筹码、下注和游戏状态
        currentPlayer.chips -= totalRaiseAmount;
        currentPlayer.currentBet = raiseAmount;
        updatedGame.pot += totalRaiseAmount;
        updatedGame.currentBet = raiseAmount;
        break;
        
      case 'fold':
        // 弃牌逻辑
        currentPlayer.hasFolded = true;
        break;
        
      case 'all-in':
        // All In逻辑
        const allInAmount = currentPlayer.chips;
        const totalAllInAmount = allInAmount + currentPlayer.currentBet;
        currentPlayer.chips = 0;
        currentPlayer.currentBet = totalAllInAmount;
        currentPlayer.isAllIn = true;
        updatedGame.pot += allInAmount;
        if (totalAllInAmount > game.currentBet) {
          updatedGame.currentBet = totalAllInAmount;
        }
        
        // 检查是否需要创建边池
        const allInPlayers = game.players.filter(p => p.isAllIn);
        if (allInPlayers.length > 1) {
          // 简单的边池逻辑：为每个All-in玩家创建单独的边池
          const sidePotAmount = Math.min(...allInPlayers.map(p => p.currentBet));
          updatedGame.sidePot = (updatedGame.sidePot || 0) + sidePotAmount;
        }
        break;
    }
    
    // 定义活跃玩家变量
    const activePlayers = game.players.filter(p => !p.hasFolded && p.chips > 0);
    const activeNonAllInPlayers = game.players.filter(p => !p.hasFolded && !p.isAllIn);
    const allPlayersHaveEqualBets = activeNonAllInPlayers.every(p => p.currentBet === updatedGame.currentBet);
    
    // 如果所有活跃玩家下注相等，或者只剩一个活跃玩家，结束当前轮次
    if ((allPlayersHaveEqualBets && activeNonAllInPlayers.length > 0) || activePlayers.length <= 1) {
      // 检查是否可以进入下一阶段或结束游戏
      if (activePlayers.length <= 1) {
        // 游戏结束逻辑
        updatedGame.phase = 'Showdown';
      } else {
        // 进入下一轮或下一阶段
        updatedGame.currentBet = 0;
        game.players.forEach(p => {
          p.currentBet = 0;
        });
        
        // 根据游戏阶段决定下一步
        switch (game.phase) {
          case 'PreFlop':
            updatedGame.phase = 'Flop';
            break;
          case 'Flop':
            updatedGame.phase = 'Turn';
            break;
          case 'Turn':
            updatedGame.phase = 'River';
            break;
          case 'River':
            updatedGame.phase = 'Showdown';
            break;
        }
        
        // 重置到第一个活跃玩家位置
        let firstActivePosition = 0;
        while (game.players[firstActivePosition].hasFolded || game.players[firstActivePosition].isAllIn) {
          firstActivePosition = (firstActivePosition + 1) % game.players.length;
        }
        updatedGame.currentPlayerPosition = firstActivePosition;
      }
    } else {
      // 移动到下一个玩家
      let nextPosition = (game.currentPlayerPosition + 1) % game.players.length;
      while (game.players[nextPosition].hasFolded || game.players[nextPosition].isAllIn) {
        nextPosition = (nextPosition + 1) % game.players.length;
      }
      updatedGame.currentPlayerPosition = nextPosition;
    }
    
    // 更新游戏状态
    const result = await updateGameState(
      Number(id),
      updatedGame.phase as any,
      updatedGame.pot,
      updatedGame.currentBet,
      updatedGame.currentPlayerPosition,
      updatedGame.communityCards || [],
      updatedGame.deck || [],
      updatedGame.sidePot
    );
    
    res.status(200).json({
      success: true,
      message: '游戏动作执行成功',
      data: {
        game: result
      }
    });
    
  } catch (error) {
    console.error('游戏动作处理错误:', error);
    res.status(500).json({
      success: false,
      message: '游戏动作处理失败'
    });
  }
};